import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../common/ScreenAdaper.dart';
import 'package:dio/dio.dart';
import '../../config/Config.dart';
import '../../widget/Tool.dart';
import '../../services/Storage.dart';

class MemberPage extends StatefulWidget {
  @override
  _MemberPageState createState() => _MemberPageState();
}

class _MemberPageState extends State<MemberPage> {
  String _token = "";
  Map _userInfo = {};
  List _bookmarkData = [];
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _getToken();
    _getUserInfo();
  }
  _getUserInfo() async{
    try {
      Map userInfo = json.decode(await Storage.getString("userInfo"));
      if(userInfo != {}){
        setState(() {
          this._userInfo=userInfo;
        });
      }
    } catch (e){
      print(e);
    }
  }
  _getToken() async{
    try{
      String token = await Storage.getString("token");
      setState(() {
        this._token=token;
      });
      _getBookmark();
    } catch (e){
      print(e);
    }
  }
  // 获取书签
  _getBookmark() async{
    var apiUrl = "${Config.domain}api/book/bookmark?token=${_token}";
    Response result=await Dio().get(apiUrl);
    var list=result.data;
    if(list['code'] == 1){
      setState(() {
        this._bookmarkData = list["data"];
      });
    }
  }
  // 删除书签
  _delBookmark(int id) async{
    var apiUrl = "${Config.domain}api/book/bookmark_del?id=${id}&token=${_token}";
    Response result=await Dio().get(apiUrl);
    var list=result.data;
    Tool.ShowToast(list['msg']);
    _getBookmark();
  }
  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          _top(),
          SizedBox(height: S.height(10),),
          Tool.TitleWidget(context, "我的书架-会员中心"),
          _case(),
        ],
      ),
    );
  }

  Widget _top(){
    return Container(
      height: S.height(280),
      decoration: BoxDecoration(
        color: Color.fromARGB(255, 244, 247, 255),
        image: DecorationImage(image: ExactAssetImage("images/user_bg.jpg"),fit:BoxFit.cover),
      ),//
      child: Row(
        children: <Widget>[
          Container(
              padding: EdgeInsets.only(left: S.width(30)),
              child: ClipOval(
                child: Image.asset(
                  'images/user.png',
                  width: S.width(180),
                  height: S.width(180),
                  fit: BoxFit.cover,
                ),
              )
          ),
          Container(
            width: S.getScreenWidth() - S.width(240),
            padding: EdgeInsets.only(left: S.width(30)),
            child: _token == "" || _token == null ? _loginBut() : _userInfoWidget(),
          )
        ],
      ),
    );
  }
  // 用户信息
  Widget _userInfoWidget(){
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        Text("${_userInfo["Username"]}",style: TextStyle(fontSize: S.size(40),color: Colors.white),maxLines: 1,overflow: TextOverflow.ellipsis,),
        Text("${_userInfo["Email"]}",style: TextStyle(fontSize: S.size(40),color: Colors.white),maxLines: 1,overflow: TextOverflow.ellipsis,),
      ],
    );
  }
  // 登录按钮
  Widget _loginBut(){
    return Row(
      children: <Widget>[
        InkWell(
          child: Text("登录",style: TextStyle(fontSize: S.size(40),color: Colors.white),),
          onTap: (){
            Navigator.pushNamed(context, "/login");
          },
        ),
        SizedBox(width: S.width(20),),
        Text("/",style: TextStyle(fontSize: S.size(40),color: Colors.white),),
        SizedBox(width: S.width(20),),
        InkWell(
          child: Text("注册",style: TextStyle(fontSize: S.size(40),color: Colors.white),),
          onTap: (){
            Navigator.pushNamed(context, "/register");
          },
        ),
      ],
    );
  }

  Widget _case(){
    return Column(
      children: _bookmarkData.map((v){
        return Column(
          children: [
            Container(
              margin: EdgeInsets.all(S.width(20.0)),
              child: GestureDetector(
                child: Row(
                  children: <Widget>[
                    Container(
                      width: S.width(200),
                      height: S.height(240),
                      child: InkWell(
                        child: Image.network("${v["Image"]}", fit: BoxFit.cover),
                        onTap: (){
                          Navigator.pushNamed(context, "/book",arguments: {
                            "bookId": v["BookId"]
                          });
                        },
                      ),
                    ),
                    Expanded(
                      flex: 1,
                      child: Container(
                        height: S.height(240),
                        margin: EdgeInsets.only(left: 10),
                        padding: EdgeInsets.only(top: S.width(20),bottom: S.width(20)),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: <Widget>[
                            Stack (
                              children: <Widget>[
                                Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                  children: <Widget>[
                                    InkWell(
                                      child: Container(
                                        width: S.width(400),
                                        child: Text("${v["Name"]}", maxLines: 1,
                                          overflow: TextOverflow.ellipsis,
                                          style: TextStyle(fontSize: S.size(30),
                                              fontWeight: FontWeight.bold),
                                        ),
                                      ),
                                      onTap: (){
                                        Navigator.pushNamed(context, "/book",arguments: {
                                          "bookId": v["BookId"]
                                        });
                                      },
                                    ),
                                    Container(
                                      padding: EdgeInsets.only(top: S.height(20)),
                                      child: Container(
                                        width: S.width(390),
                                        child: Text("作者：${v["Author"]}", maxLines: 1,
                                            overflow: TextOverflow.ellipsis,
                                            style: TextStyle(fontSize: S.size(28),
                                                color: Colors.black54)
                                        ),
                                      ),
                                    ),
                                  ],
                                ),
                                Align(
                                  alignment:Alignment.bottomRight,
                                  child: InkWell(
                                    child: Container(
                                      height: S.height(58),
                                      padding: EdgeInsets.all(5),
                                      child: Text("删除",style: TextStyle(color: Colors.red),),
                                      decoration: BoxDecoration(
                                        border: new Border.all(color: Colors.red, width: 1), // 边色与边宽度
                                        borderRadius: new BorderRadius.circular((5)), // 圆角度
                                      ),
                                    ),
                                    onTap: (){
                                      _delBookmark(v["Id"]);
                                    },
                                  ),
                                )
                              ],
                            ),
                            InkWell(
                              child: Row(
                                children: <Widget>[
                                  Text("更新到：", style: TextStyle(fontSize: S.size(28),color: Colors.black54)),
                                  Container(
                                    width: S.width(375),
                                    child: Text(
                                      "${v["Endcase"]}",
                                      style: TextStyle(fontWeight: FontWeight.bold,color: Colors.red),
                                      overflow: TextOverflow.ellipsis,
                                      maxLines: 1,
                                    ),
                                  )
                                ],
                              ),
                              onTap: (){
                                Navigator.pushNamed(context, "/content",arguments: {
                                  "articleId": v["EndcaseId"],
                                  "bookId": v["BookId"]
                                });
                              },
                            ),
                            InkWell(
                              child: Row(
                                children: <Widget>[
                                  Text("已读到：", style: TextStyle(fontSize: S.size(28),color: Colors.black54)),
                                  Container(
                                    width: S.width(370),
                                    child: Text(
                                      "${v["EndArticleName"]}",
                                      style: TextStyle(fontWeight: FontWeight.bold),
                                      overflow: TextOverflow.ellipsis,
                                      maxLines: 1,
                                    ),
                                  ),
                                ],
                              ),
                              onTap: (){
                                Navigator.pushNamed(context, "/content",arguments: {
                                  "articleId": v["ArticleId"],
                                  "bookId": v["BookId"]
                                });
                              },
                            ),
                          ],
                        ),
                      ),
                    ),
                  ],
                ),
                onTap: () {
                  //              Navigator.pushNamed(context, "/book",arguments:{"bookId":v["BookId"]});
                },
              ),
            ),
            Divider(height: 1,)
          ],
        );
      }).toList(),
    );
  }
}